package com.san.report.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.san.HtmlToPdfInterceptor;
import com.san.base.controller.BaseController;
import com.san.base.domain.CodeDO;
import com.san.base.domain.DictDO;
import com.san.base.service.CodeService;
import com.san.base.service.DictService;
import com.san.common.annotation.Log;
import com.san.common.annotation.ReportLog;
import com.san.common.utils.Constant;
import com.san.common.utils.DateUtils;
import com.san.common.utils.MD5Utils;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.metadata.domain.BusinessDataDO;
import com.san.metadata.domain.DataSourceDO;
import com.san.metadata.domain.ManageTableDO;
import com.san.metadata.service.BaseLegalPersonService;
import com.san.metadata.service.BusinessDataService;
import com.san.metadata.service.DataSourceService;
import com.san.metadata.service.ManageMetadataService;
import com.san.report.service.LegalPersonReportService;
import com.san.report.service.ReportRoleService;
import com.san.report.vo.LegalPersonReportBaseVO;
import com.san.system.domain.UserDO;
import com.san.system.service.UserService;

/**
 * 法人信用报告控制器
 * 
 * @author hulp
 *
 */
@RequestMapping("/report/legalPerson")
@Controller
public class LegalPersonReportController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(LegalPersonReportController.class);

	/**
	 * 本功能地址前缀
	 */
	private static final String PREFIX = "report/legalPerson";

	@Autowired
	BaseLegalPersonService baseLegalPersonService;

	@Autowired
	private DictService dictService;

	@Autowired
	private LegalPersonReportService legalPersonReportService;

	@Autowired
	BusinessDataService businessDataService;

	@Autowired
	ManageMetadataService manageMetadataService;

	@Autowired
	DataSourceService dataSourceService;

	@Autowired
	CodeService codeService;

	@Autowired
	ReportRoleService reportRoleService;

	@Autowired
	UserService userService;

	/**
	 * 法人信用报告列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/view")
	String LegalPersonCreditReport(Model model) {
		return PREFIX + "/view";
	}

//	/**
//	 * 法人信用报告高级查询条件
//	 * 
//	 * @param model
//	 * @return
//	 */
//	@GetMapping("/reportCondition")
//	@ResponseBody
//	String reportCondition() {
//		Map<String,Object> condition = new HashMap<String,Object>();
//		//查找范围
//		List<DictDO> searchScopeListDO = dictService.getByValue("search_scope");
//		condition.put("search_scope",searchScopeListDO);
//		
//		//行业门类
//		List<DictDO> industryCategoriesListDO = dictService.getByValue("industry_categories");
//		condition.put("industry_categories",industryCategoriesListDO);
//		
//		//成立日期
//		List<DictDO> dateOfEstablishmentListDO = dictService.getByValue("date_of_establishment");
//		condition.put("date_of_establishment",dateOfEstablishmentListDO);
//		
//		//企业状态
//		List<DictDO> enterpriseStateListDO = dictService.getByValue("enterprise_state");
//		condition.put("enterprise_state",enterpriseStateListDO);
//		
//		//注册资本
//		List<DictDO> registeredCapitalListDO = dictService.getByValue("registered_capital");
//		condition.put("registered_capital",registeredCapitalListDO);
//		
//		//资本类型
//		List<DictDO> capitalTypeListDO = dictService.getByValue("capital_type");
//		condition.put("capital_type",capitalTypeListDO);
//		
//		//资本类型
//		List<DictDO> enterprisesTypesListDO = dictService.getByValue("enterprises_types");
//		condition.put("enterprises_types",enterprisesTypesListDO);
//		
//		//信用等级
//		List<DictDO> creditRatingListDO = dictService.getByValue("credit_rating");
//		condition.put("credit_rating",creditRatingListDO);
//
//		//注册机关
//		List<DictDO> registrationAuthoritysListDO = dictService.getByValue("registration_authoritys");
//		condition.put("registration_authoritys",registrationAuthoritysListDO);
//				
//		return PREFIX + "/viewSnapshot";
//	}

	/**
	 * 法人信用快照列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/viewSnapshot/{legalPersonId}")
	String viewSnapshot(Model model, @PathVariable String legalPersonId) {
		model.addAttribute("legalPersonId", legalPersonId);
		return PREFIX + "/viewSnapshot";
	}

	/**
	 * 法人信用快照列表页
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/showSnapshot/{ssId}")
	String showSnapshot(Model model, @PathVariable String ssId) {
		model.addAttribute("ssId", ssId);
		return PREFIX + "/snapshot";
	}

	/**
	 * 法人查询列表
	 * 
	 * @param params
	 * @return
	 */
	@Log("查询法人信用报告列表")
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/list")
	@ResponseBody
	public PageUtils findListLegalPerson(String legalPersonName, String uscc, String flag, int limit, int offset) {
		PageUtils pageUtils = null;
		int page = limit / 10;
		try {
			if ("0".equals(flag)) {
				pageUtils = baseLegalPersonService.findLegalPerson(legalPersonName, uscc, true, page);
			} else {
				pageUtils = baseLegalPersonService.findLegalPerson(legalPersonName, uscc, false, page);
			}
		} catch (Exception e) {
			logger.error("获取法人列表出错", e);
		}
		return pageUtils;
	}

	/**
	 * 法人查询列表
	 * 
	 * @param params
	 * @return
	 */
	@Log("查询法人信用报告列表")
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/listNew")
	@ResponseBody
	public PageUtils findListLegalPersonNew(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			pageUtils = baseLegalPersonService.findLegalPersonByAdvancedQuery(new Query(params));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取法人列表出错", e);
		}
		return pageUtils;
	}

	/**
	 * 法人快照查询列表
	 * 
	 * @param params
	 * @return
	 */
	@Log("查询法人信用快照列表")
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/listSnapshot")
	@ResponseBody
	public PageUtils listSnapshot(String legalPersonId, int limit, int offset) {
		List<Map<String, Object>> list = null;
		try {
			list = legalPersonReportService.listSnapshot(legalPersonId, limit, offset);
		} catch (Exception e) {
			logger.error("获取快照信息列表出错", e);
		}
		return new PageUtils(list, list.size());
	}

	/**
	 * 法人信用报告详情页数据
	 * 
	 * @param legalPersonId 法人ID
	 * @return
	 */
	@Log("查询法人信用报告")
	@GetMapping("/detail")
	@ResponseBody
	R detail(String legalPersonId) {

		List<DictDO> list = dictService.getByValue(Constant.DICT_LEGAL_PERSON);
		Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
		for (DictDO i : list) {
			Map<String, Object> secondMap = new LinkedHashMap<String, Object>();
			Map<String, Object> requestMap = new LinkedHashMap<String, Object>();
			requestMap.put("parentId", i.getId());
			List<DictDO> requestList = dictService.list(requestMap);
			List<Map<String, Object>> secondResultList = null;
			for (DictDO j : requestList) {
				try {
					secondResultList = legalPersonReportService.queryBusiDataByNode(j.getId(), legalPersonId);
					secondMap.put(j.getName(), secondResultList); // 小类，第二层
				} catch (Exception e) {
					logger.error("查询法人信用报告详细信息出错", e);
				}
			}
			firstMap.put(i.getName(), secondMap); // 大类，最外层

		}
		List<Integer> paramList = new ArrayList<Integer>();
		paramList.add(Constant.BUSI_DATA_ALGORITHMTYPE_SINGLETABLE);
		paramList.add(Constant.BUSI_DATA_ALGORITHMTYPE_SPLITSTATISTICS);
		List<BusinessDataDO> busList = businessDataService.getByAlgorithmType(paramList);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("busList", busList);
		resultMap.put("detailMap", firstMap);

		R r = new R();
		r.put("code", 0);
		r.put("msg", "查询成功");
		r.put("obj", resultMap);

		return r;
	}

	/**
	 * 法人信用报告详情页
	 * 
	 * @param model
	 * @return
	 */
	@ReportLog(Constant.MODEL_TYPE_LEGAL_PERSON)
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/viewDetail/{legalPersonId}")
	String viewDetail(Model model, @PathVariable("legalPersonId") String legalPersonId) {
		model.addAttribute("legalPersonId", legalPersonId);
		String targetTableName = codeService.getByName("legal_person_base").getCodeValue();
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getByName(targetTableName);
		} catch (Exception e) {
			logger.error("获取法人信用报告基础表信息失败", e);
		}
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息失败", e);
		}
		LegalPersonReportBaseVO legalPersonReportBaseVO = null;
		try {
			legalPersonReportBaseVO = legalPersonReportService.queryBaseData(legalPersonId,
					manageTableDO.getTargetTableName(), dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取法人基础信息失败", e);
		}
		model.addAttribute("legalPersonReportBaseVO", legalPersonReportBaseVO);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 设定格式
		model.addAttribute("date", dateFormat.format(new Date()));
		model.addAttribute("timestamp", System.currentTimeMillis());
		return PREFIX + "/report";
	}

	/**
	 * 法人信用报告打印页
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("/printReport/{legalPersonId}/{number}")
	String printReport(Model model, @PathVariable("legalPersonId") String legalPersonId,
			@PathVariable("number") String number) {
		model.addAttribute("legalPersonId", legalPersonId);
		String targetTableName = codeService.getByName("legal_person_base").getCodeValue();
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getByName(targetTableName);
		} catch (Exception e) {
			logger.error("获取法人信用报告基础表信息失败", e);
		}
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息失败", e);
		}
		LegalPersonReportBaseVO legalPersonReportBaseVO = null;
		try {
			legalPersonReportBaseVO = legalPersonReportService.queryBaseData(legalPersonId,
					manageTableDO.getTargetTableName(), dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取法人基础信息失败", e);
		}
		model.addAttribute("legalPersonReportBaseVO", legalPersonReportBaseVO);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 设定格式
		model.addAttribute("date", dateFormat.format(new Date()));
		if (null != number && !"".equals(number)) {
			model.addAttribute("timestamp", number);
		} else {
			model.addAttribute("timestamp", System.currentTimeMillis());
		}
		return PREFIX + "/printReport";
	}

	/**
	 * 法人信用报告详情页详细信息
	 * 
	 * @param legalPersonId 法人ID
	 * @param busiId        业务元数据ID
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/linkReport")
	@ResponseBody
	public Map<String, Object> linkReport(@RequestParam String legalPersonId, @RequestParam String busiId) {
		BusinessDataDO businessDataDO = businessDataService.getById(Long.valueOf(busiId));
		ManageTableDO manageTableDO = null;
		DataSourceDO dataSourceDO = null;
		List<String> thList = null;
		try {
			manageTableDO = manageMetadataService.getById(businessDataDO.getTableId());
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}

		try {
			thList = manageMetadataService.listColumnByIds(businessDataDO.getDetColumnId());
		} catch (Exception e) {
			logger.error("获取表头信息出错", e);
		}

		List<Map<String, Object>> trList = null;
		try {
			trList = legalPersonReportService.queryReportList(dataSourceDO, legalPersonId,
					businessDataDO.getBusiSqldet());
		} catch (Exception e) {
			logger.error("获取详细信息出错", e);
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("th", thList);
		resultMap.put("tr", trList);
		return resultMap;
	}

	/**
	 * 二维码数据信息
	 * 
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/getQRCodeMessage")
	@ResponseBody
	public Map<String, Object> getQRCodeMessage() {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		Long userId = getUserId();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		Date date = new Date();
		map.put("userId", userId);
		map.put("time", df.format(date));
		map.put("timeStamp", date.getTime());
		return map;
	}

	/**
	 * 快照
	 * 
	 * @param batch   批次号
	 * @param type    快照类型
	 * @param content 快照内容
	 * @return
	 */
	@Log("生成法人信用快照")
	@RequiresPermissions("report:legalPerson:view")
	@PostMapping("/snapShot")
	@ResponseBody
	R snapShot(String legalPersonId, String batch, int type, String content, String QRCode) {
		boolean flag = false;
		try {
			flag = legalPersonReportService.save(legalPersonId, batch, type, content, QRCode);
		} catch (Exception e) {
			logger.error("生成快照失败", e);
		}
		if (flag) {
			return R.ok();
		}
		return R.error("生成快照失败");

	}

	/**
	 * 查询快照信息
	 * 
	 * @param ssId 快照ID
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@PostMapping("/viewSnapShot")
	@ResponseBody
	R viewSnapShot(String ssId) {
		List<Map<String, Object>> list = null;
		try {
			list = legalPersonReportService.viewSnapShot(ssId);
		} catch (Exception e) {
			logger.error("查询快照失败", e);
		}
		return R.okReturnList(list);
	}

	/**
	 * 快照
	 * 
	 * @param batch   批次号
	 * @param type    快照类型
	 * @param content 快照内容
	 * @return
	 */
	@Log("生成法人信用快照")
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/printPDF")
	@ResponseBody
	String printPDF(String legalPersonId, String number) {
		File file = new File("D:\\dytest\\test11.pdf");
		File parent = file.getParentFile();
		// 如果pdf保存路径不存在，则创建路径
		if (!parent.exists()) {
			parent.mkdirs();
		}

		StringBuilder cmd = new StringBuilder();
		// wkhtmltopdf 在系统中的路径
		cmd.append("D:\\dytest\\wkhtmltopdf\\bin\\wkhtmltopdf.exe");
		// cmd.append(" ");

		cmd.append(
				" --debug-javascript --header-html D:\\dytest\\title.html --footer-html D:\\dytest\\footer.html toc --toc-header-text \"目录\" ");

		// html路径 即目标网页路径
		cmd.append(" ");
		cmd.append("http://localhost/reportPDF/printLegalReport/" + legalPersonId + "/" + number);
		cmd.append(" ");
		// pdf保存路径
		cmd.append("D:\\dytest\\test11.pdf");

		String result = "1";
		try {
			Process proc = Runtime.getRuntime().exec(cmd.toString());
			HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
			HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
			error.start();
			output.start();
			proc.waitFor();
		} catch (Exception e) {
			result = "2";
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 法人信用报告详情页数据 - 权限分类
	 * 
	 * @param legalPersonId 法人ID
	 * @return
	 * @throws Exception
	 */
	@Log("查询法人信用报告  - 权限分类")
	@GetMapping("/detailRole")
	@ResponseBody
	R detailRole(String legalPersonId) {

		UserDO userDO;
		List<Long> dictIds = null;
		try {
			userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			dictIds = reportRoleService.dictList(deptId);
		} catch (Exception e) {
			logger.error("获取用户角色失败", e);
			R r = new R();
			r.put("code", 0);
			r.put("msg", "查询失败");
			r.put("obj", "");
			return r;
		}

		List<DictDO> list = dictService.getByValue(Constant.DICT_LEGAL_PERSON);
		Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
		for (DictDO i : list) {
			if (dictIds.contains(i.getId())) {
				Map<String, Object> secondMap = new LinkedHashMap<String, Object>();
				Map<String, Object> requestMap = new LinkedHashMap<String, Object>();
				requestMap.put("parentId", i.getId());
				List<DictDO> requestList = dictService.list(requestMap);
				List<Map<String, Object>> secondResultList = null;
				for (DictDO j : requestList) {
					if (dictIds.contains(j.getId())) {
						try {
							secondResultList = legalPersonReportService.queryBusiDataByNode(j.getId(), legalPersonId);
							secondMap.put(j.getName(), secondResultList); // 小类，第二层
						} catch (Exception e) {
							logger.error("查询法人信用报告详细信息出错", e);
						}
					}
				}
				firstMap.put(i.getName(), secondMap); // 大类，最外层
			}
		}
		List<Integer> paramList = new ArrayList<Integer>();
		paramList.add(Constant.BUSI_DATA_ALGORITHMTYPE_SINGLETABLE);
		paramList.add(Constant.BUSI_DATA_ALGORITHMTYPE_SPLITSTATISTICS);
		List<BusinessDataDO> busList = businessDataService.getByAlgorithmType(paramList);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("busList", busList);
		resultMap.put("detailMap", firstMap);

		R r = new R();
		r.put("code", 0);
		r.put("msg", "查询成功");
		r.put("obj", resultMap);

		return r;
	}

	/**
	 * 法人信用报告详情页
	 * 
	 * @param model
	 * @return
	 */
	@ReportLog(Constant.MODEL_TYPE_LEGAL_PERSON)
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/viewDetailRole/{legalPersonId}")
	String viewDetailRole(Model model, @PathVariable("legalPersonId") String legalPersonId) {
		model.addAttribute("legalPersonId", legalPersonId);
		String targetTableName = codeService.getByName("legal_person_base").getCodeValue();
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getByName(targetTableName);
		} catch (Exception e) {
			logger.error("获取法人信用报告基础表信息失败", e);
		}
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息失败", e);
		}
		LegalPersonReportBaseVO legalPersonReportBaseVO = null;
		try {
			legalPersonReportBaseVO = legalPersonReportService.queryBaseData(legalPersonId,
					manageTableDO.getTargetTableName(), dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取法人基础信息失败", e);
		}
		model.addAttribute("legalPersonReportBaseVO", legalPersonReportBaseVO);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 设定格式
		model.addAttribute("date", dateFormat.format(new Date()));
		model.addAttribute("timestamp", System.currentTimeMillis());
		return PREFIX + "/reportRole";
	}

	/**
	 * 法人信用报告详情页数据
	 * 
	 * @param legalPersonId 法人ID
	 * @return
	 */
	@Log("查询法人信用报告")
	@GetMapping("/detailNumber")
	@ResponseBody
	R detailNumber(String legalPersonId) {

		List<DictDO> list = dictService.getByValue(Constant.DICT_LEGAL_PERSON);
		Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
		for (DictDO i : list) {
			Map<String, Object> secondMap = new LinkedHashMap<String, Object>();
			Map<String, Object> requestMap = new LinkedHashMap<String, Object>();
			requestMap.put("parentId", i.getId());
			List<DictDO> requestList = dictService.list(requestMap);
			List<Map<String, Object>> secondResultList = null;
			int total = 0;
			for (DictDO j : requestList) {
				try {
					secondResultList = legalPersonReportService.queryBusiDataByNode(j.getId(), legalPersonId);
					if (secondResultList.size() > 0) {
						total++;
					}
					secondMap.put(j.getName(), secondResultList); // 小类，第二层
				} catch (Exception e) {
					logger.error("查询法人信用报告详细信息出错", e);
				}
			}
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("list", secondMap);
			temp.put("total", total);
			firstMap.put(i.getName(), temp); // 大类，最外层

		}
		List<Integer> paramList = new ArrayList<Integer>();
		paramList.add(Constant.BUSI_DATA_ALGORITHMTYPE_SINGLETABLE);
		paramList.add(Constant.BUSI_DATA_ALGORITHMTYPE_SPLITSTATISTICS);
		List<BusinessDataDO> busList = businessDataService.getByAlgorithmType(paramList);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("busList", busList);
		resultMap.put("detailMap", firstMap);

		String targetTableName = codeService.getByName("legal_person_base").getCodeValue();
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getByName(targetTableName);
		} catch (Exception e) {
			logger.error("获取法人信用报告基础表信息失败", e);
		}
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息失败", e);
		}
		LegalPersonReportBaseVO legalPersonReportBaseVO = null;
		try {
			legalPersonReportBaseVO = legalPersonReportService.queryBaseData(legalPersonId,
					manageTableDO.getTargetTableName(), dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取法人基础信息失败", e);
		}

		resultMap.put("legalPersonReportBaseVO", legalPersonReportBaseVO);

		R r = new R();
		r.put("code", 0);
		r.put("msg", "查询成功");
		r.put("obj", resultMap);

		return r;
	}

	/**
	 * 法人信用报告详情页
	 * 
	 * @param model
	 * @return
	 */
	@ReportLog(Constant.MODEL_TYPE_LEGAL_PERSON)
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/xyda/{legalPersonId}")
	String xyda(Model model, @PathVariable("legalPersonId") String legalPersonId) {
		model.addAttribute("timestamp", System.currentTimeMillis());
		model.addAttribute("legalPersonId", legalPersonId);
		return PREFIX + "/xyda";
	}

	/**
	 * 法人信用报告详情页详细信息
	 * 
	 * @param legalPersonId 法人ID
	 * @param busiId        业务元数据ID
	 * @return
	 */
	@RequiresPermissions("report:legalPerson:view")
	@GetMapping("/linkReportCharts")
	@ResponseBody
	public Map<String, Object> linkReportCharts(@RequestParam String legalPersonId, @RequestParam String busiId) {
		BusinessDataDO businessDataDO = businessDataService.getById(Long.valueOf(busiId));
		ManageTableDO manageTableDO = null;
		DataSourceDO dataSourceDO = null;
		List<String> thList = null;
		try {
			manageTableDO = manageMetadataService.getById(businessDataDO.getTableId());
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(manageTableDO.getTargetSourceId());
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}

		try {
			thList = manageMetadataService.listColumnByIds(businessDataDO.getDetColumnId());
		} catch (Exception e) {
			logger.error("获取表头信息出错", e);
		}

		List<Map<String, Object>> trList = null;
		try {
			trList = legalPersonReportService.queryReportList(dataSourceDO, legalPersonId,
					businessDataDO.getBusiSqldet());
		} catch (Exception e) {
			logger.error("获取详细信息出错", e);
		}

		List<LinkedList<?>> list = new LinkedList<LinkedList<?>>();
		LinkedList<Object> secondList = null;
		for (Map<String, Object> i : trList) {
			secondList = new LinkedList<Object>();
			for (Object value : i.values()) {
				secondList.add(value);
			}
			list.add(secondList);
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("th", thList);
		resultMap.put("tr", list);

		// 拓展部分
		List<Map<String, Object>> tuozhan = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for (LinkedList<?> k : list) {
			map = new HashMap<String, Object>();
			for (int z = 0; z < thList.size(); z++) {
				map.put(thList.get(z), k.get(z));
			}
			tuozhan.add(map);
		}

		resultMap.put("tuozhan", tuozhan);
		return resultMap;
	}

	
	/**
	 * 企查查查询接口
	 * @param qymc
	 * @param busiId
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/queryQiChacha")
	@ResponseBody
	public JSONObject queryQiChacha(String companyName, Long busiId) throws Exception {

		CodeDO apiKeyCode = codeService.getByName(Constant.QICHACHA_API_KEY);
		String apiKey = apiKeyCode.getCodeValue();
		CodeDO secretKeyCode = codeService.getByName(Constant.QICHACHA_SECRETKEY);
		String secretKey = secretKeyCode.getCodeValue();

		BusinessDataDO business = businessDataService.getById(busiId);
		String url = Constant.QICHACHA_DOMAIN + "/" + business.getSpringBean() + "&dtype=json";
		url = url.replace("<companyName>", companyName).replace("<ApiKey>", apiKey);

		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet(url);

		String timespan = DateUtils.getUnixTimespan();

		String key = apiKey + timespan + secretKey;

		String token = MD5Utils.MD5Encode(key);
		httpGet.setHeader("Token", token);
		httpGet.setHeader("Timespan", timespan);

		HttpResponse response = client.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();

		StringBuilder sb = new StringBuilder();
		if (statusCode == 200) {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			String buffer = null;
			while ((buffer = reader.readLine()) != null) {
				sb.append(buffer);
			}
		}

		JSONObject object = JSONObject.parseObject(sb.toString());
		Object result = object.get("Result");
		JSONObject name = JSON.parseObject(business.getBusiDesc()); // 获取键名中文名

		JSONObject resultJson = new JSONObject();
		resultJson.put("name", name);
		resultJson.put("result", result);

		return resultJson;
	}


}